package org.exaple.laixe;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;


import android.R.array;
import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.opengl.Visibility;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class Thi extends Activity{
	
	private ArrayList<Integer> Questions = new ArrayList<Integer>();// Store 30 questions
	private ArrayList<Integer> Answers = new ArrayList<Integer>();// store 30 answers
	private ArrayList<Integer> Corrects = new ArrayList<Integer>();// store 30 correct answer(1-4)
	
	private RadioGroup rdAnswer;
	private RadioButton rd_1;
	private RadioButton rd_2;
	private RadioButton rd_3;
	private RadioButton rd_4;
	private WebView webView_thi;	
	private Button btn_thiNext;
	private Button btn_thiBack;	
	private String currentQuestion; 	// Current Question(1-405)
	private int currentNumberofAnswers;	// Current number of Answers(1/2/3/4) of current Question
	private int indexof30;			// current Index of Question(0-29)
	//private Button btn1;
	private TextView QuestionNavigation;	// Text control to display current question /30
	private LinearLayout Container30Questions;
	private TextView timeRemaining;
	
	private int scale; 	// store scale for webview  in next questions
	private long millisUntilFinished;
	private CountDownTimer countDown; 
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.thi);
        
        
        rdAnswer = (RadioGroup) findViewById(R.id.exam_radio_group);
        rd_1 = (RadioButton) findViewById(R.id.exam_radio_1);
        rd_2 = (RadioButton) findViewById(R.id.exam_radio_2);
        rd_3 = (RadioButton) findViewById(R.id.exam_radio_3);
        rd_4 = (RadioButton) findViewById(R.id.exam_radio_4);
        webView_thi = (WebView) findViewById(R.id.webView_thi);
        btn_thiNext = (Button) findViewById(R.id.exam_Next_button);
        btn_thiBack = (Button) findViewById(R.id.exam_Back_button);
        //
        QuestionNavigation = (TextView) findViewById(R.id.ExamTitleBar_QuestionInfo);
        Container30Questions = (LinearLayout) findViewById(R.id.ExamTitleBar_30QuestionsContainer);
        timeRemaining = (TextView) findViewById(R.id.ExamTitleBar_TimeRemaining);        
        
        
        Container30Questions.setOnClickListener( new View.OnClickListener() {
			
			public void onClick(View v) {				
				Toast.makeText(getBaseContext(), "Clicked 30 ?", Toast.LENGTH_SHORT).show();
			}
		});
        
        
        
        
        // Set zoom control       
        webView_thi.getSettings().setSupportZoom(true);//Zoom Control on web (You don't need this 
         											//if ROM supports Multi-Touch
        webView_thi.getSettings().setBuiltInZoomControls(true); //Enable Multitouch if supported by ROM
        webView_thi.getSettings().setUseWideViewPort(true);  
        // Turn on javascript
        webView_thi.getSettings().setJavaScriptEnabled( true );
        
        
        System.out.println(Questions.toString());
        
        
        // handle to process RadioGroup 
        rdAnswer.setOnCheckedChangeListener( new RadioGroup.OnCheckedChangeListener() {
			
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				 if(rd_1.isChecked() ){
					 Answers.set( indexof30, 1);
					 update1QuestionButtonState( indexof30, QuestionState.ANSWERED);
				 }
				 else if(rd_2.isChecked()) {
					 Answers.set(indexof30, 2);
					 update1QuestionButtonState( indexof30, QuestionState.ANSWERED);
				 }
				 else if(rd_3.isChecked()) {
					 Answers.set(indexof30, 3);
					 update1QuestionButtonState( indexof30, QuestionState.ANSWERED);
				 }
				 else if(rd_4.isChecked()) {
					 Answers.set(indexof30, 4);
					 update1QuestionButtonState( indexof30, QuestionState.ANSWERED);
				 }
			}
		});
        // handle to process button Back
        btn_thiBack.setOnClickListener( new View.OnClickListener() {
			
			public void onClick(View v) {				
				if(indexof30 > 0) {
					indexof30 -- ;
					currentQuestion = Questions.get(indexof30).toString(); 
					ProcessQuestionString();
					ShowQuestion( String.valueOf(currentQuestion) );
					
				}
			}
		});
        // handle to process button Next
        btn_thiNext.setOnClickListener( new View.OnClickListener() {
			
			public void onClick(View v) {
				if( indexof30 < 29) {
					indexof30 ++ ;
					currentQuestion = Questions.get(indexof30).toString();
					ProcessQuestionString();
					ShowQuestion( String.valueOf(currentQuestion) );				
				}
			}
		});        
        
        // Display 30 questions = 30 buttons
        add30QuestionButtons();
        
        if(savedInstanceState != null) {
        	
        }
        else {
        	indexof30 = 0;
        	// Chose random 30 Questions with rules 
            Choose30Questions();
            // Choose 30 Correct Answers;
            ChooseCorrectAnswers();
            //System.out.println("móa");
            System.out.println(Corrects.toString());           
            //
            millisUntilFinished = 1200000;
            timeRemaining.setText("1200");
            // khởi tao tất cả kết quả ban đầu đều là 0
            for (int i = 0; i < 30; i++) {
    			Answers.add(0);
    		}           
            //
            currentQuestion = Questions.get(indexof30).toString();
            System.out.println(Questions.toString());
            // Show Question number 1
            ProcessQuestionString();
            ShowQuestion( String.valueOf(currentQuestion) );  
            
            // sẽ gọi hàm onResume để start countdowntimer
        }
	}
	
	// Create Option Menu
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.thi_menu, menu);
		return true;
	}
		
	// Process When user click on Option emnu
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.exam_menuThietLap:
			startActivity(new Intent(this, Prefs.class));
			return true;
		case R.id.exam_menuHuongDan:
			startActivity(new Intent(this, Thi_help.class));
			return true;
		case R.id.exam_menuKetThuc:
			onExit();
			default:
				return super.onOptionsItemSelected(item);
			}
		}

	public void showResult() {
		// store Questions, Answers in database
		DBIncorrectQuestions dbHelper = new DBIncorrectQuestions(this);
        dbHelper.open();
        boolean isCorrect = false;
        for (int i = 0; i < 30; i++) {
			if(Corrects.get(i) == Answers.get(i))
				isCorrect = true;
			else 
				isCorrect = false;
			
            // store the result to DB, then we can list most incorrect answer later
            dbHelper.increaseResult(String.valueOf(Questions.get(i)), isCorrect);
        }
        dbHelper.close();
	    
	    //
		Intent result = new Intent();
		Bundle b = new Bundle();
		b.putIntegerArrayList("Answers", Answers);
		b.putIntegerArrayList("Questions", Questions);
		b.putIntegerArrayList("Corrects", Corrects);
		b.putLong( "time", Long.parseLong( (timeRemaining.getText().toString() ) ) );
		result.setClass(this, Result.class);
		result.putExtras(b);
		startActivity(result);
	}
	
	// Event Back button when users press
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)  {
	    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {System.out.println(currentQuestion);
	        if(indexof30 == 0 ) {
	        	// asking user to exit if they are viewing the first question
	        	System.out.println(indexof30);
	        	onExit();
	        } else {
	        	previous();
	        }
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {System.out.println("Goi ham onSave");
		countDown.cancel();
		savedInstanceState.putInt( "currentQuestionIndex", indexof30);		// Store Current Question Index
		savedInstanceState.putString("currentQuestion", currentQuestion);
		savedInstanceState.putIntegerArrayList("Answers", Answers);			// Store Answers
		savedInstanceState.putIntegerArrayList("Corrects", Corrects);		// Store correct Answers
		savedInstanceState.putIntegerArrayList("Questions", Questions); 	// Store Questions
		savedInstanceState.putLong("timeremaining", Long.parseLong( (timeRemaining.getText().toString() ) ) * 1000 );	// store time remaining
		millisUntilFinished = Long.parseLong( (timeRemaining.getText().toString() ) ) * 1000 ;		
	}
	
	@Override 
	public void onRestoreInstanceState(Bundle state) {
		System.out.println("Goi ham onRestore");
		indexof30 = state.getInt("currentQuestionIndex");
		Answers = state.getIntegerArrayList("Answers");
		Corrects = state.getIntegerArrayList("Corrects");
		Questions = state.getIntegerArrayList("Questions");
		currentQuestion = state.getString("currentQuestion");
		millisUntilFinished = state.getLong("timeremaining");		
		// update 30 Question navigation buttons state
        for (int i = 0; i < Answers.size(); i++) {
			update1QuestionButtonState(i, Answers.get(i) == 0 ? QuestionState.UNANSWERED : QuestionState.ANSWERED );
		}
        // Show current Question
		ProcessQuestionString();
        ShowQuestion( String.valueOf(currentQuestion) );
		super.onRestoreInstanceState(state);
	}
	
	@Override
	public void onResume() {
		System.out.println("Goi ham onResume");
		super.onResume();
		Music.play(this, "file:///sdcard/data/org.exaple.laixe/loitotinhmuaxuan.mp3");
		// start new counDown timer								
				System.out.println(millisUntilFinished);
				countDown = new CountDownTimer(millisUntilFinished, 1000) {
		        	
		            public void onTick(long millisUntilFinished) {
		                timeRemaining.setText("" + millisUntilFinished / 1000);
		                
		            }

		            public void onFinish() {
		                timeRemaining.setText("0");
		                AlertCountDownTimer();
		                
		            }
		        };
				countDown.start();
	}
	
	@Override
	public void onPause() {
		System.out.println("Goi ham onPause");
		super.onPause();
		Music.stop(this);
		
	}
	
	public void AlertCountDownTimer() {
		AlertDialog.Builder builder = new AlertDialog.Builder(Thi.this);
		builder.setMessage(R.string.timeup_message)
		       .setCancelable(false)
		       .setTitle(R.string.timeup_title)
		       .setPositiveButton(R.string.timeup_button, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   	showResult();
		                finish();
		           }
		       })
		       .setIcon(R.drawable.ic_menu_sad);
		AlertDialog alert = builder.create();		
		alert.show();
	}
	
	
	private void onExit() {		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(R.string.exam_thoatMessage)
		       .setCancelable(false)
		       .setTitle(R.string.exam_thoatTtile)
		       .setPositiveButton(R.string.exam_thoatbtnYes, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   	showResult();
		                finish();
		           }
		       })
		       .setNegativeButton(R.string.examThoatbtnNo, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       })
		       .setIcon(R.drawable.ic_dialog_info);
		AlertDialog alert = builder.create();		
		alert.show();
	}
	
	private void previous() {
		if(indexof30 > 0) {
			indexof30 -- ;
			currentQuestion = Questions.get(indexof30).toString(); 
			ProcessQuestionString();
			ShowQuestion( String.valueOf(currentQuestion) );
			
		}
	}

	
	// Choose "quatity" questions from "start" to "end"
	public void ChooseQuestions(int quatity, int start, int end) {
		Random ran = new Random();
		int iNew;
		int Start_Quality = 0;
		while( Start_Quality < quatity ) {
			iNew = rdInt(end - start +1) + start;
			if( !Questions.contains( iNew ) ) {
				Start_Quality ++;
				Questions.add(iNew);
			}
		}
		
	}
	
	// Random between 0 and b
	public int rdInt(int b){
		Random random = new Random();
		int result = random.nextInt() % b;	
		return Math.abs(result);
	}
	
	/* random between a and b
	
	public int rdInt(int a, int b){
		Random random = new Random();
		
		while (true){
			int result = random.nextInt() % b;
			if (result >= a){
				return result;
			}
		}
	}
	*/
	
	// Choose 30 questions and store in arraylist Questions
	public void Choose30Questions() {
			// Read file b1.dat or b2.dat to choose Questions
			try {
				// Open File to Read
				InputStream ins;
				if( Laixe.hang == "B1") 
					ins = getApplicationContext().getAssets().open( "b1.dat" );
				else
					ins = getApplicationContext().getAssets().open( "b2.dat" );
				InputStreamReader inputReader = new InputStreamReader(ins);
				BufferedReader bufferReader = new BufferedReader(inputReader);
				
				// Read every line of file
				String line;
				while( (line = bufferReader.readLine()) != null ){
					// process string line 
					String[] a = line.split( ";");
					ChooseQuestions( Integer.parseInt(a[0]), 
							Integer.parseInt(a[1]), Integer.parseInt(a[2]) );
				}
				
			}
			catch( IOException io) {
				io.printStackTrace();
			}
		
		
	}
	
	// Process string "Question" 
	public void ProcessQuestionString() {
		int currentQues = Integer.parseInt(currentQuestion);		
		String current = "";
		if( currentQues <= 0 )
			currentQues = 1;
		if( currentQues >= 405)
			currentQues = 405;
		
		if( currentQues >= 1 && currentQues <= 9)
			current = "0" + "0" + String.valueOf( currentQues );
		else if( currentQues >=10 && currentQues <=99 )
			current  = "0" + String.valueOf( currentQues );
		else 
			current = String.valueOf( currentQues );
		
		currentQuestion = current;
	}
	
	// Show questions in webView
	public void ShowQuestion(String number) {
    	String baseUrl = "file:///sdcard/data/org.exaple.laixe/";
    	String data = getStringFromURL( number + ".html");
    	// Display current question
    	scale = (int)(100 * webView_thi.getScale()); // keep the last zoom ratio
    	webView_thi.loadDataWithBaseURL(baseUrl, data, "text/html", "utf-8", "");
    	webView_thi.setInitialScale(scale);
    	//show Answer
    	currentNumberofAnswers = data.split("</li><li class=").length;
    	// Show current question in titleBar
    	QuestionNavigation.setText( String.valueOf(indexof30 + 1) + "/30");
    	// 
    	DoAfterChangingQuestion();
    	//
    	System.out.println(Answers.get(indexof30));
    	System.out.println(Answers.toString());
    }
    
    // Read File from Assets and return to a string to process later
    public String getStringFromURL(String s) {
    	String str = "";
    	try {
	    	InputStream is = getApplicationContext().getAssets().open(s);
	    	InputStreamReader input = new InputStreamReader(is);
	    	int charRead;	    	
	    	char[] bufer = new char[2000];
	    	while( (charRead = input.read(bufer)) > 0 ) {
	    		String readString = String.copyValueOf(bufer, 0, charRead);
	    		str += readString;
	    		bufer = new char[2000];
	    	}
	    	is.close();
    	}
    	catch(IOException io) {
    		io.printStackTrace();
    	}    	
    	
    	return str;
    }
    
    public void ChooseCorrectAnswers() {
    	System.out.println("móa");
    	String a;    	
    	for (int i = 0; i < 30; i++) {
			if(Questions.get(i) >= 1 && Questions.get(i) <= 9)
				a = "00" + Questions.get(i);
			else if(Questions.get(i) >= 10 && Questions.get(i) <= 99)
				a= "0" + Questions.get(i);
			else
				a = String.valueOf(Questions.get(i));
			
			String data = getStringFromURL(  a + ".html");
			String b[] = data.split("</li><li class=");
			for (int j = 0; j < b.length; j++) {
				if( b[j].contains("correct.png")) {
					System.out.println(b[j].contains("correct.png") );
					Corrects.add(j+1);
				}
			}
		}
    	
    }
    
    public void SetVisibilityforRadio() {
    	// Invi
    	switch (currentNumberofAnswers) {
		case 1:
			rd_1.setVisibility(1);
			rd_2.setVisibility(-1);
			rd_3.setVisibility(-1);
			rd_4.setVisibility(-1);
			break;
		case 2:
			rd_1.setVisibility(1);
			rd_2.setVisibility(1);
			rd_3.setVisibility(-1);
			rd_4.setVisibility(-1);
			break;			
		case 3:			
			rd_1.setVisibility(1);
			rd_2.setVisibility(1);
			rd_3.setVisibility(1);
			rd_4.setVisibility(-1);
			break;
		case 4:
			rd_1.setVisibility(1);
			rd_2.setVisibility(1);
			rd_3.setVisibility(1);
			rd_4.setVisibility(1);
			break;

		default:
			break;
		}
    }
    
    public void SetCheckedForRadio(){
    	// Checked    	
    	switch ( Answers.get(indexof30)) {
		case 1:			
			
			rd_1.setChecked(true);
			rd_2.setChecked(false);
			rd_3.setChecked(false);
			rd_4.setChecked(false);
			break;
		case 2:
			rd_1.setChecked(false);
			rd_2.setChecked(true);
			rd_3.setChecked(false);
			rd_4.setChecked(false);
			break;
		case 3:
			rd_1.setChecked(false);
			rd_2.setChecked(false);
			rd_3.setChecked(true);
			rd_4.setChecked(false);
			break;
		case 4:
			rd_1.setChecked(false);
			rd_2.setChecked(false);
			rd_3.setChecked(false);
			rd_4.setChecked(true);
			break;
		default:
			break;
		}
    }
    
    // Set ...
    public void DoAfterChangingQuestion() {
    	
    	// process RadioGroup Answer(check and invi)    	
    	SetVisibilityforRadio();    	  	
    	rdAnswer.clearCheck();
    	SetCheckedForRadio();    	
    	
    	// Update 30 Questions = change colors 
    	
    }    
    

		/**
	 * Update state for a question button in navigation section
	 * @param button Question button to update UI
	 * @param state New state for questions
	 */
    private void update1QuestionButtonState(Button button, QuestionState state) {
        if(state == QuestionState.ANSWERED) {
                button.setBackgroundResource(R.color.titleBar_answered_question);
        } else {
                button.setBackgroundResource(R.color.titleBar_unanswered_question);
        }
	}

		/**
		 * Update state for a question, looking by question index, which starts from zero
		 * @param questionIndex Index of question to update state, which starts from zero
		 * @param state New state for questions
		 */
	private void update1QuestionButtonState(int questionIndex, QuestionState state) {
        int lineNumber = (questionIndex / 10) + 1;
        int buttonIndex = questionIndex % 10;
        
        LinearLayout line;
        switch (lineNumber) {
        case 1:
                line = (LinearLayout)findViewById(R.id.ExamTitleBar_10Questions_Row1);
                break;
        case 2:
                line = (LinearLayout)findViewById(R.id.ExamTitleBar_10Questions_Row2);
                break;
        default:
                line = (LinearLayout)findViewById(R.id.ExamTitleBar_10Questions_Row3);
                break;
        }
        update1QuestionButtonState((Button)line.getChildAt(buttonIndex), state);
        
        //quickActionMenu.updateQuestionState(questionIndex, state);
	}

    
    
    
    /**
     * Add 30 question navigation buttons to the status bar on top
     */
    private void add30QuestionButtons() {
            LinearLayout container = (LinearLayout)findViewById(R.id.ExamTitleBar_30QuestionsContainer);
            int count = container.getChildCount();	// =3(0,1,2) (trong LinearLayout TitleBar_30QuestionsContainer chứa 3 cái container con )
            for(int x = 0; x < count; x++) {
                    add10QuestionButtonsForALine((LinearLayout)container.getChildAt(x), x);	//(0,1,2)
            }
    }
    
    /**
     * Add 10 questions navigation buttons to a line, which is a LinearLayout
     * @param line A buttons container to add button to
     * @param lineIndex Index of line
     */
    private void add10QuestionButtonsForALine(LinearLayout line, int lineIndex) {
            Button button;
            int start = lineIndex * 10;
            int end = start + 10;
            for(int x = start; x < end; x++) {
                    final int index = x;
                    //System.out.println("dsfdsfdsfdsfdsfdsfdsfds");
                    // create a button from template
                    button = (Button)getLayoutInflater().inflate(R.layout.button_titlebar, line, false);
                    // add that button to the linearlayout
                    button.setId(x);
                    line.addView(button);
                    // Add click event for this button, to show quick action menu / question chosen
                    button.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                            	
                            	// Display Action menu to choose 30 Questions
                                    //context.vibrateIfEnabled();
                                    //quickActionMenu.show();
                                    //quickActionMenu.setSelectedQuestion(currentQuestionIndex);
                            	
                            	// Display  Question chosen right now
                            	for (int i = 0; i < 30; i++) {
									if(i == v.getId() )  {
										indexof30 = i ;
										currentQuestion = Questions.get(indexof30).toString(); 
										ProcessQuestionString();
										ShowQuestion( String.valueOf(currentQuestion) );
										
									}
										
								}
                            	
                            }
                    });
                    /*
                    // add another button to quick action menu
                    QuestionActionItem questionButton = new QuestionActionItem();
                    questionButton.setTitle(String.valueOf(index + 1));
                    //chart.setIcon(getResources().getDrawable(R.drawable.chart));
                    questionButton.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                    context.vibrateIfEnabled();
                                    currentQuestionIndex = index;
                                    showQuestion(currentQuestionIndex);
                                    quickActionMenu.dismiss();
                            }
                    });
                    quickActionMenu.addActionItem(questionButton);
                    
                    */
            }
    }
}
